package com.highveldsky.gwtdatabinding.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.highveldsky.gwtdatabinding.client.controller.CarController;
import com.highveldsky.gwtdatabinding.client.service.CarService;
import com.highveldsky.gwtdatabinding.client.service.CarServiceAsync;
import com.highveldsky.gwtdatabinding.client.view.CarEdit;
import com.highveldsky.gwtdatabinding.shared.model.Car;

public class Gwt_data_binding implements EntryPoint {

	private DockLayoutPanel dockPanel;
	private FlowPanel centerPanel;
	private FlowPanel westPanel;
	private FlowPanel northPanel;
	private FlowPanel southPanel;
	private CarController controller;
	private final CarServiceAsync carService = GWT.create(CarService.class);	

	public void onModuleLoad() {
		dockPanel = new DockLayoutPanel(Unit.EM);
		centerPanel = new FlowPanel();
		westPanel = new FlowPanel();
		northPanel = new FlowPanel();
		southPanel = new FlowPanel();
		dockPanel.addStyleName("gwt-data-binding-dock-panel");
		dockPanel.addNorth(northPanel, 10);
		dockPanel.addWest(westPanel, 15);
		dockPanel.addSouth(southPanel, 5);
		dockPanel.add(centerPanel);
		initHeader();
		initFooter();
		initWestNav();		
		initCenter();		
		RootLayoutPanel rp = RootLayoutPanel.get();
		rp.add(dockPanel);	
		controller = new CarController(carService);
	}

	private void initCenter() {
		centerPanel.addStyleName("gwt-data-binding-panel");
	}

	private void initWestNav() {
		Anchor newCar = new Anchor("New Car");
		newCar.addClickHandler(new NewCar());
		westPanel.addStyleName("gwt-data-binding-panel");
		westPanel.addStyleName("gwt-data-binding-west-panel");
		westPanel.add(newCar);
	}

	private void initFooter() {
		HTML header = new HTML("Footer");
		header.addStyleName("gwt-data-binding-footer");
		southPanel.add(header);
		southPanel.addStyleName("gwt-data-binding-panel");
		southPanel.addStyleName("gwt-data-binding-south-panel");
	}

	private void initHeader() {
		HTML header = new HTML("Cars");
		header.addStyleName("gwt-data-binding-header-text");
		northPanel.add(header);
		northPanel.addStyleName("gwt-data-binding-panel");
		northPanel.addStyleName("gwt-data-binding-header-panel");
	}

	class NewCar implements ClickHandler {
		@Override
		public void onClick(ClickEvent event) {
			Car car = new Car();
			CarEdit carEdit = new CarEdit(controller, car);
			centerPanel.clear();
			centerPanel.add(carEdit);
		}
	}
}
